package com.example.springbootmybatis.config;

import com.example.springbootmybatis.bean.User;
import com.example.springbootmybatis.services.UserServices;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserServices userServices;
    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权----->>");
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
      //  info.addStringPermission("user:add");
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();  //拿到uesr对象
        //设置添加用户的权限
        info.addStringPermission(principal.getPerms());
        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证----->>");
        //用户名，密码从数据库中取
//        String name="wang";
//        String pass="123";
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userServices.selectByname(token.getUsername());
        if(user.getName()==null){
            return null; //抛出异常  UnknownAccountException 用户名报错异常
        }

        //登录成功标识
        SecurityUtils.getSubject()
                     .getSession()
                     .setAttribute("login","loginFlag");
//        Subject subject = SecurityUtils.getSubject();
//        Session subjectSession = subject.getSession();
//        subjectSession.setAttribute("login","loginFlag");
        //密码不用自己判断  shrio内部已经判断
                                            //传进去这个user 上面的授权就能拿到登录对象了
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
